<template>
  <div id="app">
    <van-nav-bar title="注册" class="page-nav-bar" ></van-nav-bar>
    <div class="article-detail">
     <div class="article-content-card">
      <div  class="login-btn">
        <img class="mobile-img" src="../../public/login.png" alt="" />
      </div>
      <van-form @submit="onSubmit" >
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="用户名"
            label="用户名"  
            placeholder="请输入用户名"
            :rules="userFormRules.userName"
          />
          <van-field
            v-model="realname"
            name="真实姓名"
            label="真实姓名"
            placeholder="请输入你的真实姓名，注意：不可更改"
            :rules="userFormRules.realName"
          />
          <van-field name="radio" label="性别">
            <template #input>
              <van-radio-group v-model="gender" direction="horizontal">
                <van-radio name="男">男</van-radio>
                <van-radio name="女">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-model="email"
            name="邮箱账号"
            label="邮箱账号"
            placeholder="请输入你的邮箱"
            :rules="userFormRules.email"
          />
          <van-field
            v-model="mobile"
            name="手机号码"
            label="手机号码"
            placeholder="请输入你的手机号"
            :rules="userFormRules.mobile"
          />
          <van-field
            v-model="password"
            type="password"
            name="密码"
            label="密码"
            placeholder="请输入密码"
            :rules="userFormRules.password"
          />
          <van-field
            v-model="password2"
            type="password"
            name="确认密码"
            label="确认密码"
            placeholder="请再次输入密码"
            :rules="userFormRules.password2"
          />
          <van-field
            v-model="emailCode"
            center
            clearable
            label="邮箱验证码"
            placeholder="请输入邮箱验证码"
          >
            <template #button>
              <van-button size="small" type="primary" :disabled="isSending" @click="sendEmailCode   ">{{ buttonText }}</van-button>
            </template>
          </van-field>
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="success" native-type="submit">
            注册
          </van-button>
        </div>
      </van-form>
      <div style="margin: 16px;">
        <van-button round block type="primary"  @click="router.push('/login');">
          已有账号？去登录
        </van-button>
      </div>
    </div>
  </div>
  </div>
</template>

<script>
import {nextTick} from "vue";
import {Toast} from "vant";
import {regSendMail,regsubmit} from "../../api/user";
import router from "../../router";
//1.构建登录请求
//获取用户输入内容

export default {
  data() {
    return {
      username: '',
      realname: '',
      gender: '男',
      email: '',
      mobile: '',
      password: '',
      password2: '',
      emailCode: '',
      isSending: false, // 是否正在发送验证码
      countDownSeconds: 60, // 倒计时秒数
      router,
      userFormRules: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '用户名长度在 6 到 20 个字符', trigger: 'blur' },
        ],
        realName: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator:this.validateEmail,trigger:'blur',message:'邮箱不合法'},
        ],
        mobile: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号码',
            trigger: ['blur', 'change'],
          },
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
        ],
        password2: [
          { required: true, message: '确认密码不能为空', trigger: 'blur' },
          { validator: this.checkPassword, trigger: 'blur' ,message: '两次密码输入不一致', },
        ],
      },
    };
  },
  computed: {
    buttonText() {
      return this.isSending ? `${this.countDownSeconds}s` : '发送验证码';
    }
  },
  methods: {
  validateEmail() {
  const regex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if(!regex.test(this.email)){
    return false;
  }
},
    checkPassword() {
      if (this.password2 !== this.password) {
        return false;
      }
    },
    onSubmit() {
      const param={
        username:this.username,
        password:this.password,
        email:this.email,
        phone:this.mobile,
        emailCode:this.emailCode,
        realname:this.realname,
        sex:this.gender
      };
      // console.log(data);
      regsubmit(param).then((res)=>{
        if(res.data.code==20000){
          Toast.success(res.data.data);
         nextTick(()=>{
            router.replace('/login');
          })
       
      
        }else{
          Toast(res.data.msg);
        }
      });
      // this.$refs.form.validate((valid) => {
      //   if (valid) {
      //     const data=this.$refs.form.formData;

          
      //     // TODO: 表单验证通过，提交注册信息
      //   } else {
      //     // TODO: 表单验证失败，提示错误信息
      //     return false;
      //   }
      // });
    },
    sendEmailCode() {
      const regex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  if(!regex.test(this.email)){
    Toast("邮箱不合法");
    return;
  }
      if (this.isSending) {
        return;
      }
      try {
        regSendMail(this.email).then((res)=>{
        
        if(res.data.code==20000){
          Toast.success("发送成功，1分钟内如收不到请再次尝试");
        }else{
          Toast.error("发送失败了，请检查你的网络！");
        }

      });
        // 开始倒计时
        this.isSending = true;
        const timer = setInterval(() => {
          if (this.countDownSeconds > 0) {
            this.countDownSeconds -= 1;
          } else {
            this.isSending = false;
            this.countDownSeconds = 60;
            clearInterval(timer);
          }
        }, 1000);
      } catch (error) {
        // 发送验证码失败
        console.error(error);
      }

      // TODO: 发送邮箱验证码
    },
  },
};
</script>
<style>
.article-content-card {
  padding: 24px;
  background-color: #fff;
  border-radius: 0px;
  box-shadow: 0px 4px 16px rgba(0, 0, 0, 0.08);
  margin-top: 10px;
}

.article-source-card {
  background-color: #3f64ca;
  color: #fff;
  padding: 8px 16px;
  border-radius: 16px;
  display: inline-block;
}

.article-time-card {
  margin-left: 16px;
  display: inline-block;
} 
.mobile-img {
      width: 132px;
      height: 132px;
      margin-bottom: 15px;
    }
.login-btn {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
</style>